package game;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Vector;


public class ItemContainer implements Cloneable
{
	final int DEFAULT_MAX_WEIGHT = 214748364,DEFAULT_MAX_ITEM_COUNT = 214748364;
	
	ArrayList<Item> itemList;
	int maxItemCount,maxWeight,itemCount,weight;
	Vector<ActionListener> listeners = new Vector<ActionListener>();
	
	public ItemContainer(int maxItemCount,int maxWeight)
	{
		itemList = new ArrayList<Item>();
		this.maxItemCount = maxItemCount;
		this.maxWeight = maxWeight;
	}
	
	public ItemContainer(Vector<Item> list, int maxItemCount,int maxWeight)
	{
		itemList = new ArrayList<Item>();
		itemList.addAll(list);
		recalcWeight();
		this.maxItemCount = maxItemCount;
		this.maxWeight = maxWeight;
	}
	
	public ItemContainer()
	{
		itemList = new ArrayList<Item>();
		maxItemCount = DEFAULT_MAX_ITEM_COUNT;
		maxWeight = DEFAULT_MAX_WEIGHT;
	}
	
	public void addActionListener(ActionListener al)
	{
		listeners.add(al);
	}
	
	public void removeActionListener(ActionListener al)
	{
		listeners.remove(al);
	}
	
	private void notifyListeners(String text, Object source)
	{
		ActionEvent ae = new ActionEvent(source, 0, text);
		for(int i = 0; i < listeners.size(); ++i)
			listeners.get(i).actionPerformed(ae);
	}
	
	public void Add(Item item)
	{
		if(item.weight + weight <= maxWeight && itemCount < maxItemCount) 
		{
			itemList.add(item);
			weight += item.weight;
			itemCount++;
			notifyListeners("item-add", item);
		}
	}
	
	public void Remove(Item item)
	{
		if(itemList.contains(item))
		{
			itemList.remove(item);
			itemCount--;
			weight -= item.weight;
			notifyListeners("item-remove", item);
		}
	}
	
	private void recalcWeight()
	{
		weight = 0;
		for(Item i : itemList)
			weight += i.getWeight();
	}
	
	public boolean CanAdd(Item item)
	{
		return (item.weight + weight <= maxWeight && itemCount < maxItemCount);
	}
	
	public boolean Contains(Item item)
	{
		return itemList.contains(item);
	}
	
	public boolean IsEmpty()
	{
		return itemCount == 0;
	}

	public int getMaxItemCount() 
	{
		return maxItemCount;
	}

	public void setMaxItemCount(int maxItemCount) 
	{
		this.maxItemCount = maxItemCount;
	}

	public int getMaxWeight() 
	{
		return maxWeight;
	}

	public void setMaxWeight(int maxWeight) 
	{
		this.maxWeight = maxWeight;
	}

	public int getWeight() 
	{
		return weight;
	}

	public int getItemCount() 
	{
		return itemCount;
	}
	
	public ArrayList<Item> GetItemList()
	{
		return itemList;
	}

	public Object clone()
    {
		ItemContainer ic = new ItemContainer(maxItemCount, maxItemCount);
		for(Item i : itemList)
			try {
				ic.Add(i.clone());
			} catch (CloneNotSupportedException e) {}
		return ic;
	}
}
